package tracker

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"goDFS/etc"
	"goDFS/public"
	ncf "goDFS/synchronization"
	"io/ioutil"
	"net/http"
)

var (
	Conf         *etc.Conf        //配置文件
	loadBalancer *LoadBalancer    //负载均衡器
	syncManager  *ncf.SyncManager //同步管理器
)

//心跳测试包
func Heartbeat(addr *public.StorageAddr) bool {

	server := fmt.Sprintf("http://%s/heartbeat", addr.GetAddr())
	resp, err := http.Get(server)
	if err != nil {
		etc.SaveLog("[ Heartbeat ]"+err.Error(), 3)

		return false
	}

	defer resp.Body.Close()
	_, err = ioutil.ReadAll(resp.Body)
	if err != nil {
		etc.SaveLog("[ Heartbeat ]"+err.Error(), 3)
		fmt.Println("read from resp.Body failed,err:", err)
		return false
	} else {
		return true
	}
}

//开始服务的入口
func Service(conf *etc.Conf) {

	//初始化配置文件
	Conf = conf
	etc.CreatLogFile(Conf.GetStorage()) //创建日志器
	trackerConf := conf.GetTracker()

	loadBalancer = NewLoadBalancer(Heartbeat) //创建负载均衡器
	syncManager = ncf.NewSyncManage()

	go loadBalancer.MaintainingAddress() //维护Address

	//开启同步
	go syncManager.StartSync(loadBalancer.GetAddress())

	server := gin.Default()

	//开启静态文件服务
	if conf.GetTracker().Web != "" { //开启静态文件服务
		server.Static("/static", fmt.Sprintf("%s/%s", trackerConf.Web, "static"))
		server.GET("/", func(c *gin.Context) {
			c.File(fmt.Sprintf("%s/%s", trackerConf.Web, "index.html"))
		})
	}

	fileAip := server.Group(public.ApiGroupName)

	//使用中间件来阻止没有storage时候的请求
	fileAip.Use(func(c *gin.Context) {
		if loadBalancer.Length() == 0 {
			etc.SaveLog("[ Service ]"+public.NotStorageServer, 3)
			c.JSON(http.StatusInternalServerError, public.NewJsonErrUse(1, public.NotStorageServer))
			c.Abort()
		}

	})

	//接口服务
	server.GET(RegisterApi, Register)
	{
		fileAip.GET(GetTokenApi, GetToken)          //返回token
		fileAip.GET(GetApi, GetRed)                 //为用户的下载请求重定向
		server.GET(GetAllAddressApi, GetAllAddress) //返回全部的storage
		server.GET(public.SyncFileApi, SyncFile)    //同步接口
	}
	////启动服务
	addr := fmt.Sprintf("%s:%d", trackerConf.Host, trackerConf.Port)
	server.Run(addr)
}
